//
//  BaseTableViewController.swift
//  SinaNews
//
//  Created by hroot on 15/8/13.
//  Copyright (c) 2015年 Lily. All rights reserved.
//

import UIKit
let kScreenSize:CGSize = UIScreen.mainScreen().bounds.size
class BaseTableViewController: UITableViewController, ViewWillShow {

    var type: String?
    var manager: AFHTTPRequestOperationManager?
    var dataArr: NSMutableArray?
    var advArr: NSMutableArray?
    var adView: ADView?
    var containerController: AppContainerViewController?
    override func viewDidLoad() {
        super.viewDidLoad()

        self.dataArr = NSMutableArray()
        self.advArr = NSMutableArray()
        self.manager = AFHTTPRequestOperationManager()
        self.manager?.responseSerializer = AFHTTPResponseSerializer()
        self.navigationController?.tabBarController?.tabBar.translucent = true
        self.tableView.registerNib(UINib(nibName: "NewsSingleCell", bundle: nil), forCellReuseIdentifier: "NewsSingleCell")
        self.tableView.registerNib(UINib(nibName: "NewsThreeCell", bundle: nil), forCellReuseIdentifier: "NewsThreeCell")
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "creatAdView", name: "advArrChanged", object: nil)
    }

    func loadData() {
        var tabBarController = UIApplication.sharedApplication().windows[0].rootViewController as! UITabBarController
        var partUrl:String?
        switch tabBarController.selectedIndex {
        case 0:
            partUrl = "http://api.sina.cn/sinago/list.json?channel=news_"
        case 1:
            partUrl = ""
        case 2:
            partUrl = ""
        case 3:
            partUrl = ""
        default:
            partUrl = "http://api.sina.cn/sinago/list.json?channel=news_"
        }
        addTask(partUrl! + self.type!)
    }
    func addTask(url: String) -> Void {

        //避免强引用循环
        unowned var weakSelf:BaseTableViewController = self
        
        self.manager?.GET(url, parameters: nil, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
            if (responseObject != nil) {
                var dict: AnyObject! = NSJSONSerialization.JSONObjectWithData(responseObject as! NSData, options: NSJSONReadingOptions.AllowFragments, error: nil)
                //println(dict!)
                var responseDict = dict as! NSDictionary
                var dataDict = responseDict.valueForKey("data") as! NSDictionary
                var listArr = dataDict.valueForKey("list") as! NSArray
                for modelDict in listArr {
                    var model = NewsModel()
                    model.setValuesForKeysWithDictionary(modelDict as! [NSObject : AnyObject])
//                    if (modelDict["is_focus"] == ) {
//                        
//                    }
                    if (model.is_focus != nil) {
                        weakSelf.advArr!.addObject(model)
                    } else {
                        weakSelf.dataArr?.addObject(model)
                    }
                }
                if (weakSelf.advArr?.count > 0) {
                    NSNotificationCenter.defaultCenter().postNotificationName("advArrChanged", object: nil)
                }
                weakSelf.tableView.reloadData()
            }
            }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
            println("下载失败")
        })
        
    }
    
    func creatAdView(arr: NSArray) {
        var adView = ADView(frame: CGRectMake(0, 0, kScreenSize.width, 170))
        adView.creatView(arr)
        self.tableView.tableHeaderView = adView
    }
    
    func viewWillShow() {
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArr!.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var model = self.dataArr![indexPath.row] as! NewsModel
        if (model.pics != nil) {
            var cell1 = tableView.dequeueReusableCellWithIdentifier("NewsThreeCell", forIndexPath: indexPath) as! NewsThreeCell
            cell1.showData(model)
            return cell1
        } else {
            var cell2 = tableView.dequeueReusableCellWithIdentifier("NewsSingleCell", forIndexPath: indexPath) as! NewsSingleCell
            cell2.showData(model)
            return cell2
        }
        return UITableViewCell()
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 135
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        var detail = DetailViewController()
        var model = self.dataArr![indexPath.row] as! NewsModel
        detail.url = model.link
        detail.containerController = self.containerController
        self.containerController?.navigationController?.pushViewController(detail, animated: true)
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
